package org.itboys.manage.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.itboys.admin.dto.AdminUserData;
import org.itboys.admin.entity.AdminUser;
import org.itboys.commons.utils.cookie.CookieUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.manage.constant.AdminConstants;
import org.itboys.manage.constant.AdminCookieConstant;
import org.itboys.manage.constant.AdminSessionConstant;
import org.itboys.manage.utils.AdminSessionHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.entity.EntityIdDB;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.service.IDGeneratorService;
import org.itboys.redis.RedisCacheClient;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 商家登陆账号
 * @author weisky
 *
 */
@Service
public class ManagerUserService extends BaseService<AdminUser, Long>{

    private static final long serialVersionUID = 1L;

    private static final String SHOP_ID_KEY = "USER_SHOP_ID-";
    private static final int SHOP_ID_EXPIRE = 24 * 3600;

    @Resource(name = "sellerDS")
    private MongoDataSource ds;

    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private RedisCacheClient redisCacheClient;
    @Autowired
    private IDGeneratorService idGeneratorService;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<AdminUser> getEntityClass() {
        return AdminUser.class;
    }

    /**
     * 修改商家账号的状态
     * @param sellerUserId
     * @param state 0：冻结  1：开通
     * @return
     */
    public boolean updateState(Long sellerUserId, int state){
        try{
            update(sellerUserId, "state", state);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerUserService.updateState error", e);
            return false;
        }
    }

    /**
     * 登陆
     * @param userName
     * @param password
     * @param response
     * @return
     */
    public int login(String userName, String password, HttpServletResponse response){
        try{

            AdminUser adminUser = getByField("username", userName);
            if(adminUser == null){
                return -1;//用户不存在
            }
            if(!StringUtils.equals(adminUser.getPassword(), Digests.md5(password))){
                logger.warn("商家账号登陆异常：账号名："+userName+"，登陆密码："+password+"，密码不匹配");
                return -2;//密码不正确
            }
            adminUser.setLoginTime(System.currentTimeMillis());//登陆时间
            adminUser.setLoginIp(AdminSessionHolder.getLoginIp());//登陆IP
            update(adminUser);//修改登陆人的登陆时间和IP

            CookieUtils.addCookie(response, AdminCookieConstant.COOKIE_USER_NAME, userName, 864000);
            ServletContextHolder.getSession().setAttribute(AdminSessionConstant.SESSION_USER_ID, adminUser.getId());
            ServletContextHolder.getSession().setAttribute(AdminSessionConstant.SITE_ACCOUNT_ID, adminUser.getUsername());
            ServletContextHolder.getSession().setMaxInactiveInterval(Integer.valueOf(resourceHolder.getStringValue("sessionMaxInactiveInterval")));//设置session有效时间
            return AdminConstants.ACTION_SUCCESS;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerUserService.login error", e);
            return AdminConstants.ACTION_FAIL;//操作失败
        }
    }

    /**
     * 删除
     * @param sellerUserId
     * @return
     */
    public boolean dele(Long sellerUserId){
        try{
            super.delete(sellerUserId);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("SellerUserService.dele error", e);
            return false;
        }
    }

    /**
     * 根据用户名查询用户
     *
     * @return
     */
    public AdminUser getAdminUser(String username) {
        // 用户名转小写再查
        List<AdminUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("username", username).asList();
        return list==null||list.isEmpty()?null:list.get(0);
    }

    /**
     * 根据用户名查询用户
     *
     * @return
     */
    public AdminUser getAdminUserByUserId(long userId) {
        // 用户名转小写再查
        List<AdminUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("userId", userId).asList();
        return list==null||list.isEmpty()?null:list.get(0);
    }

    /**
     * 根据手机号查询用户
     *
     * @return
     */
    public AdminUser getAdminUserByPhone(String phone) {
        // 用户名转小写再查
        List<AdminUser> list = ds.createQuery(getEntityClass()).filter("isDeleted", 0).filter("phone", phone).asList();
        return list==null||list.isEmpty()?null:list.get(0);
    }

    public String getHQAccount(String accountId) {
        return "HQ" + accountId;
    }

    public long genUid() {
        Query<EntityIdDB> q = ds.createQuery(EntityIdDB.class);
        UpdateOperations<EntityIdDB> update = ds.createUpdateOperations(EntityIdDB.class).inc("currentId");
        EntityIdDB counter = ds.findAndModify(q, update, false, true);
        return idGeneratorService.getNextId(counter.getCurrentId());
    }

    public List<AdminUser> getByAccountId(List<String> accountIds) {
        if (CollectionUtils.isEmpty(accountIds)) {
            return Collections.emptyList();
        }
        return ds.createQuery(getEntityClass()).field("accountId").in(accountIds).asList();
    }

    public List<AdminUser> queryInfo(String sellerUserName, int offset, int limit) {
        return ds.createQuery(getEntityClass()).field("sellerUserName").equal(sellerUserName).offset(offset).limit(limit).order("-ct").asList();

    }

    public long totalInfo(String sellerUserName) {
        return ds.createQuery(getEntityClass()).field("sellerUserName").equal(sellerUserName).countAll();
    }

}
